<template>
  <div class="upload-input">
    <div v-show="!showProgress" style="width: 100%; display: flex; align-items: center; position: relative">
      <Upload
        action="/"
        :before-upload="handleUpload"
        :max-size="51200"
        :show-upload-list="false"
        :format="format"
        :on-success="handleUploadSuccess"
        :on-exceeded-size="handleMaxSize"
        :on-format-error="handleFormatError"
        :style="{ width }"
        type="drag"
      >
        <!--            <Button icon="ios-cloud-upload-outline">Select the file to upload</Button> -->
        <Input
          placeholder="请选择需要导入的文件"
          suffix="ios-folder-outline"
          readonly
          :value="file ? file.name : ''"
        />
      </Upload>
      <div style="margin-left: 10px">
        支持xlsx文件，单个文件不得大于1M
      </div>
    </div>
    <div v-if="errorMsg" class="err-msg">
      {{ errorMsg }}
    </div>
    <div
      v-show="showSheet"
      id="luckysheet"
      style="
                margin: 0px;
                padding: 0px;
                position: absolute;
                width: 100%;
                height: 80%;
                left: 0px;
                top: 120px;
                display: none;
            "
    />
    <div
      v-show="showProgress"
      style="
                width: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-around;
            "
    >
      <span>正在导入数据，请勿关闭页面</span>
      <Progress :percent="percent" :stroke-width="20" :stroke-color="['#108ee9', '#87d068']" status="active" />
    </div>
  </div>
</template>

<script>
import LuckyExcel from 'luckyexcel'
import cloneDeep from 'lodash/cloneDeep'
import { checkDate } from '../../libs/dateFmt'

let thisLockRow = [1]
export default {
  name: 'UploadInput',
  props: {
    lockRow: {
      default() {
        return 1
      },
      type: Number,
    },
    beanFieldEnum: {
      default: '',
      type: String,
    },
    requireField: {
      default() {
        return []
      },
      type: Array,
    },
    width: {
      type: String,
      default: '340px',
    },
  },
  data() {
    return {
      percent: 10,
      file: null,
      headers: {},
      format: ['xlsx'],
      showProgress: false,
      showSheet: false,
      changeExcelOption: {
        container: 'luckysheet',
        showtoolbar: false,
        showsheetbar: false, //是否显示底部sheet页按钮
        allowCopy: true,
        userInfo: true,
        hook: {
          //狗子函数
          cellUpdateBefore(r, c, v, f) {
            //监听单元格修改之前
            if (r < thisLockRow) 
              return false
                        

            return true
          },
        },
      },
      fieldEnum: [],
      errorMsg: '',
      interval: null,
    }
  },
  watch: {
    lockRow(v) {
      thisLockRow = v
    },
  },
  mounted() {
    this.fieldEnum = cloneDeep(this.getEnums(this.beanFieldEnum))
    // if (this.beanFieldEnum === 'importStudentFieldsEnum' && this.systemVersion !== 2) 
    //   this.fieldEnum.pop()
        
    // if (this.beanFieldEnum === 'importStudentFieldsEnum' && this.systemVersion === 2) 
    //   this.fieldEnum[this.fieldEnum.length - 1].code = 23
        
    this.init()
  },
  beforeUnmount() {
    clearInterval(this.interval)
    this.init()
  },
  methods: {
    autoAddProgress() {
      clearInterval(this.interval)
      const that = this
      this.interval = setInterval(() => {
        const random = Math.floor(Math.random() * 20)
        if (random + that.percent > 100) {
          that.percent = 100
          clearInterval(this.interval)
        }
        else {
          that.percent += random
        }
      }, 300)
    },
    finish() {
      this.percent = 100
    },
    init() {
      this.percent = 10
      this.showProgress = false
      this.file = null
      this.changeExcelOption.data = []
      this.changeExcelOption.title = ''

      window.luckysheet.destroy()
      this.showSheet = false
      this.errorMsg = ''
    },
    initBack() {
      this.percent = 10
      this.showProgress = false
      this.changeExcelOption.data = []
      this.changeExcelOption.title = ''

      window.luckysheet.destroy()
    },
    /**
     * 创建excel工作簿
     */
    createSheet() {
      const file = this.file
      return new Promise((resolve, reject) => {
        LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
          if (exportJson.sheets === null || exportJson.sheets.length === 0) {
            this.$Message.error('无法读取excel文件的内容，当前不支持xls文件！')
            return
          }
          window.luckysheet.destroy()

          this.changeExcelOption.data = exportJson.sheets
          this.changeExcelOption.title = file.name.substring(0, file.name.indexOf('.xlsx'))
          window.luckysheet.create(this.changeExcelOption)
          resolve(this.getData(exportJson.sheets[0].data))
        })
        this.showProgress = true
      })

      // this.showSheet = true;
    },

    checkFile() {
      if (!this.file) 
        return false
            
      return true
    },
    getExcelData() {
      const file = this.file
      return new Promise((resolve, reject) => {
        LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
          if (exportJson.sheets === null || exportJson.sheets.length === 0) {
            this.$Message.error('无法读取excel文件的内容，当前不支持xls文件！')
            return
          }
          window.luckysheet.destroy()

          this.changeExcelOption.data = exportJson.sheets
          this.changeExcelOption.title = file.name.substring(0, file.name.indexOf('.xlsx'))
          window.luckysheet.create(this.changeExcelOption)
          resolve(this.getData(exportJson.sheets[0].data))
        })
        this.showProgress = true
        this.autoAddProgress()
      })
    },
    checkRightFile(data) {
      let errorMsg = ''
      const row = data[this.lockRow - 1]
      let i
      for (i = 0; i < row.length; i++) {
        if (!row[i]) 
          break
                
      }
      if (i != this.fieldEnum.length) 
        errorMsg = '导入的表格，与模板不匹配。请下载模板，重新编辑上传；'
            
      this.errorMsg += errorMsg
      return errorMsg
    },
    getData(data) {
      this.errorMsg = ''
      let msg = ''
      msg += this.checkRightFile(data)
      if (msg) {
        return {
          status: false,
          msg,
        }
      }
      // let sheetsData = window.luckysheet.getAllSheets();
      // let data = sheetsData[0].data;
      const objList = []
      for (let i = this.lockRow; i < data.length; i++) {
        const obj = {}
        const row = data[i]
        for (const f of this.fieldEnum) {
          if (row[f.code] && row[f.code].m) 
            obj[f.value] = row[f.code].m
                    
        }
        if (Object.keys(obj).length !== 0) 
          objList.push(obj)
                
      }
      console.log(objList)
      if (!objList || objList.length === 0) {
        msg += '请上传正确文件数据'
        this.errorMsg += msg
        return {
          status: false,
          msg,
        }
      }
      msg += this.checkRequireField(objList)
      if (msg) {
        return {
          status: false,
          msg,
        }
      }
      else {
        return {
          status: true,
          objList,
        }
      }
    },
    checkRequireField(objList) {
      let errorMsg = ''
      if (!objList || objList.size === 0) {
        errorMsg += '请导入正确的模板文件；'
      }
      else {
        const nameMobileMap = {}
        const mobileMap = {}
        objList.forEach((o, index) => {
          for (const f of this.requireField) {
            const field = this.fieldEnum.find(e => e.value === f)
            if (!field) 
              continue
                        
            if (!o[f]) 
              errorMsg += `第${  index + 1  }行【${  field.name  }】不可为空；`
                        
          }
          if (o.birthdayStr) {
            const checkBirthday = checkDate(o.birthdayStr)
            if (!checkBirthday) 
              errorMsg += `第${  index + 1  }行【生日】格式错误；`
                        
          }
          if (o.integral) {
            if (!this.isInteger(Number(o.integral))) {
              errorMsg += `第${  index + 1  }行【积分】请输入整数；`
            }
            else {
              if (Number(o.integral) > 999999 || Number(o.integral) < 0) 
                errorMsg += `第${  index + 1  }行【积分】请输入0~999999范围内整数；`
                            
            }
          }
          if (o.bodyWeight) {
            if (!this.isInteger(Number(o.bodyWeight))) {
              errorMsg += `第${  index + 1  }行【体重】请输入整数；`
            }
            else {
              if (Number(o.bodyWeight) > 999) 
                errorMsg += `第${  index + 1  }行【体重】请输入三位以内数字；`
                            
            }
          }
          if (o.bodyHeight) {
            if (!this.isInteger(Number(o.bodyHeight))) {
              errorMsg += `第${  index + 1  }行【身高】请输入整数；`
            }
            else {
              if (Number(o.bodyHeight) > 999) 
                errorMsg += `第${  index + 1  }行【身高】请输入三位以内数字；`
                            
            }
          }
          if (o.mobile) {
            const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
            if (!o.mobile.includes('*')) {
              if (!reg.test(o.mobile)) 
                errorMsg += `第${  index + 1  }行【联系电话】格式错误；`
                            
            }
          }

          const key = `【${o.name}】【${o.mobile}】`
          if (!nameMobileMap[key]) 
            nameMobileMap[key] = []
                    
          nameMobileMap[key].push(o)

          const mobileKey = `【${o.mobile}】`
          if (!mobileMap[mobileKey]) 
            mobileMap[mobileKey] = []
                    
          mobileMap[mobileKey].push(o)
        })
        // for (let [key, value] of Object.entries(nameMobileMap)) {
        //     if (value.length > 1) {
        //         errorMsg += key + '学员重复；'
        //     }
        // }
      }
      this.errorMsg += errorMsg
      return errorMsg
    },
    isInteger(obj) {
      return typeof obj === 'number' && obj % 1 === 0
    },
    handleUpload(file) {
      this.errorMsg = ''
      let check = true
      if (file.size > 1024 * 1024) {
        this.errorMsg = '请上传1MB以内的xlsx文件'
        check = false
      }
      const fileType = file.name.split('.')
      const type = fileType[fileType.length - 1]
      if (!this.format.includes(type)) {
        this.errorMsg = `【${  file.name  }】文件格式不支持，当前只支持【${  this.format  }】格式`
        check = false
      }
      this.$emit('checkExcel', check)
      this.file = file
      return false
    },
    handleUploadSuccess(res) {
      if (res.success) 
        this.uploadImage.push(res.data)
      else 
        this.$Message.error('文件上传失败')
            
    },
    handleMaxSize(file) {
      this.file = null
      this.errorMsg = '请上传1MB以内的xlsx文件'
      this.$Message.error({
        content: this.errorMsg,
        duration: 3,
      })
    },
    handleFormatError(file) {
      this.file = null
      this.errorMsg = `【${  file.name  }】文件格式不支持，当前只支持【${  this.format  }】格式`
      this.$Message.error({
        content: this.errorMsg,
        duration: 3,
      })
    },
  },
}
</script>

<style lang="less" scoped>
.upload-input {
    background-color: #eeeeeeff;
    padding: var(--sp-gap);
    box-sizing: border-box;
    display: flex;
    border-radius: calc(var(--sp-radius) * 1.5);
    height: 120px;
    margin: var(--sp-gap) 0;
    flex-direction: column;
    justify-content: center;
    .err-msg {
        color: red;
        margin-top: 10px;
    }
}
</style>
